import type { DecodeResult } from './qrDecoder'

const STORAGE_KEY = 'qr_decode_history'
const MAX_HISTORY_SIZE = 100

/**
 * 历史记录管理器
 */
export class HistoryManager {
  /**
   * 获取所有历史记录
   * @returns 历史记录数组
   */
  static getHistory(): DecodeResult[] {
    try {
      const historyStr = localStorage.getItem(STORAGE_KEY)
      if (!historyStr) {
        return []
      }
      
      const history = JSON.parse(historyStr) as DecodeResult[]
      // 按时间戳降序排列（最新的在前）
      return history.sort((a, b) => b.timestamp - a.timestamp)
    } catch (error) {
      console.error('获取历史记录失败:', error)
      return []
    }
  }
  
  /**
   * 添加新的解码记录
   * @param result 解码结果
   */
  static addRecord(result: DecodeResult): void {
    try {
      const history = this.getHistory()
      
      // 检查是否已存在相同内容的记录（避免重复）
      const existingIndex = history.findIndex(item => 
        item.content === result.content && 
        item.type === result.type
      )
      
      if (existingIndex !== -1) {
        // 如果存在相同记录，更新时间戳并移到最前面
        history[existingIndex].timestamp = result.timestamp
        const updatedRecord = history.splice(existingIndex, 1)[0]
        history.unshift(updatedRecord)
      } else {
        // 添加新记录到最前面
        history.unshift(result)
      }
      
      // 限制历史记录数量
      if (history.length > MAX_HISTORY_SIZE) {
        history.splice(MAX_HISTORY_SIZE)
      }
      
      localStorage.setItem(STORAGE_KEY, JSON.stringify(history))
    } catch (error) {
      console.error('保存历史记录失败:', error)
    }
  }
  
  /**
   * 删除指定的历史记录
   * @param id 记录ID
   */
  static deleteRecord(id: string): void {
    try {
      const history = this.getHistory()
      const filteredHistory = history.filter(item => item.id !== id)
      localStorage.setItem(STORAGE_KEY, JSON.stringify(filteredHistory))
    } catch (error) {
      console.error('删除历史记录失败:', error)
    }
  }
  
  /**
   * 清空所有历史记录
   */
  static clearHistory(): void {
    try {
      localStorage.removeItem(STORAGE_KEY)
    } catch (error) {
      console.error('清空历史记录失败:', error)
    }
  }
  
  /**
   * 获取分页历史记录
   * @param page 页码（从1开始）
   * @param pageSize 每页数量
   * @returns 分页结果
   */
  static getPagedHistory(page: number = 1, pageSize: number = 10): {
    data: DecodeResult[]
    total: number
    page: number
    pageSize: number
    totalPages: number
  } {
    const allHistory = this.getHistory()
    const total = allHistory.length
    const totalPages = Math.ceil(total / pageSize)
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    const data = allHistory.slice(startIndex, endIndex)
    
    return {
      data,
      total,
      page,
      pageSize,
      totalPages
    }
  }
  
  /**
   * 搜索历史记录
   * @param keyword 搜索关键词
   * @returns 匹配的历史记录
   */
  static searchHistory(keyword: string): DecodeResult[] {
    if (!keyword.trim()) {
      return this.getHistory()
    }
    
    const history = this.getHistory()
    const lowerKeyword = keyword.toLowerCase()
    
    return history.filter(item => 
      item.content.toLowerCase().includes(lowerKeyword) ||
      item.type.toLowerCase().includes(lowerKeyword)
    )
  }
  
  /**
   * 按类型筛选历史记录
   * @param type 二维码类型
   * @returns 指定类型的历史记录
   */
  static filterByType(type: string): DecodeResult[] {
    const history = this.getHistory()
    return history.filter(item => item.type === type)
  }
  
  /**
   * 按来源筛选历史记录
   * @param source 来源类型
   * @returns 指定来源的历史记录
   */
  static filterBySource(source: 'upload' | 'camera'): DecodeResult[] {
    const history = this.getHistory()
    return history.filter(item => item.source === source)
  }
  
  /**
   * 获取历史记录统计信息
   * @returns 统计信息
   */
  static getStatistics(): {
    total: number
    byType: Record<string, number>
    bySource: Record<string, number>
    recentCount: number // 最近7天的记录数
  } {
    const history = this.getHistory()
    const now = Date.now()
    const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000
    
    const byType: Record<string, number> = {}
    const bySource: Record<string, number> = {}
    let recentCount = 0
    
    history.forEach(item => {
      // 按类型统计
      byType[item.type] = (byType[item.type] || 0) + 1
      
      // 按来源统计
      bySource[item.source] = (bySource[item.source] || 0) + 1
      
      // 最近7天统计
      if (item.timestamp >= sevenDaysAgo) {
        recentCount++
      }
    })
    
    return {
      total: history.length,
      byType,
      bySource,
      recentCount
    }
  }
  
  /**
   * 导出历史记录为JSON
   * @returns JSON字符串
   */
  static exportHistory(): string {
    const history = this.getHistory()
    const exportData = {
      exportTime: new Date().toISOString(),
      version: '1.0',
      data: history
    }
    return JSON.stringify(exportData, null, 2)
  }
  
  /**
   * 从JSON导入历史记录
   * @param jsonStr JSON字符串
   * @param merge 是否与现有记录合并
   * @returns 导入结果
   */
  static importHistory(jsonStr: string, merge: boolean = true): {
    success: boolean
    message: string
    importedCount?: number
  } {
    try {
      const importData = JSON.parse(jsonStr)
      
      if (!importData.data || !Array.isArray(importData.data)) {
        return {
          success: false,
          message: '无效的导入数据格式'
        }
      }
      
      const importedRecords = importData.data as DecodeResult[]
      
      // 验证数据格式
      const isValidFormat = importedRecords.every(record => 
        record.id && 
        record.content && 
        record.type && 
        record.timestamp && 
        record.source
      )
      
      if (!isValidFormat) {
        return {
          success: false,
          message: '导入数据格式不正确'
        }
      }
      
      if (merge) {
        // 合并模式：与现有记录合并
        const existingHistory = this.getHistory()
        const mergedHistory = [...importedRecords, ...existingHistory]
        
        // 去重（基于内容和类型）
        const uniqueHistory = mergedHistory.filter((record, index, array) => 
          array.findIndex(item => 
            item.content === record.content && 
            item.type === record.type
          ) === index
        )
        
        // 按时间戳排序并限制数量
        const sortedHistory = uniqueHistory
          .sort((a, b) => b.timestamp - a.timestamp)
          .slice(0, MAX_HISTORY_SIZE)
        
        localStorage.setItem(STORAGE_KEY, JSON.stringify(sortedHistory))
      } else {
        // 替换模式：完全替换现有记录
        const sortedRecords = importedRecords
          .sort((a, b) => b.timestamp - a.timestamp)
          .slice(0, MAX_HISTORY_SIZE)
        
        localStorage.setItem(STORAGE_KEY, JSON.stringify(sortedRecords))
      }
      
      return {
        success: true,
        message: '导入成功',
        importedCount: importedRecords.length
      }
    } catch (error) {
      return {
        success: false,
        message: '导入失败: ' + (error instanceof Error ? error.message : '未知错误')
      }
    }
  }
  
  /**
   * 获取存储使用情况
   * @returns 存储信息
   */
  static getStorageInfo(): {
    used: number // 已使用字节数
    available: number // 可用字节数（估算）
    percentage: number // 使用百分比
  } {
    try {
      const historyStr = localStorage.getItem(STORAGE_KEY) || ''
      const used = new Blob([historyStr]).size
      
      // localStorage通常限制为5-10MB，这里假设5MB
      const totalLimit = 5 * 1024 * 1024
      const available = totalLimit - used
      const percentage = (used / totalLimit) * 100
      
      return {
        used,
        available: Math.max(0, available),
        percentage: Math.min(100, percentage)
      }
    } catch (error) {
      console.error('获取存储信息失败:', error)
      return {
        used: 0,
        available: 5 * 1024 * 1024,
        percentage: 0
      }
    }
  }
}

/**
 * 格式化文件大小
 * @param bytes 字节数
 * @returns 格式化后的大小字符串
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 格式化时间差
 * @param timestamp 时间戳
 * @returns 相对时间字符串
 */
export const formatRelativeTime = (timestamp: number): string => {
  const now = Date.now()
  const diff = now - timestamp
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  const year = 365 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}